package newtest;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

public class UploadPortraitPicDemo {

    static String httpProtocol = "http";
    static String username = "";//中银保信提供的对接账号
    static String password = "";//中银保信提供的对接账号的密码
    static String ip = "";//中银保信双录服务器IP地址
    static int port = 0;//中银保信双录服务器端口号
    static HttpHost target = null;

    /**
     * 待上传文件的fileMimeType值的说明：
     *      文件类型    mimeType值
     *      .jpg 	    image/jpg
     *      .png 	    image/png
     */
    public static void main(String[] args) throws Exception {
        String counterPhone = "15012740018";//营销员手机号码
        String filePath = "E:\\sl_video\\11.png";//本地图片路径
        String type = "2";//图片类型  1-肖像  2-执业证  3-身份证
        String fileMimeType = "image/png";//根据图片类型，选择对应的fileMimeType值（参考下方注释）
        /**
         * 待上传文件的fileMimeType值的说明：
         *      文件类型    mimeType值
         *      .jpg 	    image/jpg
         *      .png 	    image/png
         */
        processRequest(counterPhone, filePath, type, fileMimeType);
    }

    private static void processRequest(String counterPhone, String filePath, String type, String fileMimeType) throws IOException
    {
        CloseableHttpClient httpclient = createSSLClientDefault();
        try {
            HttpClientContext localContext = HttpClientContext.create();
            HttpPost httpPost = new HttpPost(httpProtocol + "://" + ip + ":" + port + "/join/userPortrait/update");
            File file = new File(filePath);
            if(!file.exists()){
                System.out.print("文件不存在!");
                return;
            }
            StringBody bodyCounterPhone = new StringBody(counterPhone, ContentType.TEXT_PLAIN);
            StringBody bodyType = new StringBody(type, ContentType.TEXT_PLAIN);
            FileBody bin = new FileBody(file, ContentType.create(fileMimeType, Consts.UTF_8));

            HttpEntity entity = MultipartEntityBuilder
                    .create()
                    .setCharset(Charset.forName("utf-8"))
                    .addPart("file", bin)
                    .addPart("counterPhone", bodyCounterPhone)
                    .addPart("type", bodyType)
                    .build();
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpclient.execute(target, httpPost, localContext);
            try {
                System.out.println("------------------userPortrait----------------------");
                StatusLine tLine = response.getStatusLine();
                System.out.println(tLine);
                HttpEntity responseEntity = response.getEntity();
                String data = IOUtils.toString(responseEntity.getContent(), "UTF-8");
                System.out.println(data);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

    static CloseableHttpClient httpSSlClient = null;
    /**
     * 获取受信任httpClient
     *
     * @return
     */
    public static CloseableHttpClient createSSLClientDefault() {
        if (target == null)
            target = new HttpHost(ip, port, httpProtocol);
        if (httpSSlClient != null)
            return httpSSlClient;
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(username, GetMD5.GetMD5Code(password)));
        SSLContext sslContext;

        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" },
                    null, new NoopHostnameVerifier());
            httpSSlClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(credsProvider)
                    .build();
            return httpSSlClient;
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return null;
    }
}
